const express = require('express')
const multer = require('multer')
const LessonPlanController = require('../controllers/lessonPlanController')
const { authenticateToken, requireAdmin } = require('../middleware/auth')
const { validateRequest } = require('../middleware/validation')
const { body, query } = require('express-validator')

// 配置multer用于文件上传
const upload = multer({ dest: 'uploads/' })

const router = express.Router()

// 验证规则
const convertDocToMdValidation = [
  body('inputPath').notEmpty().withMessage('输入路径不能为空'),
  body('outputPath').notEmpty().withMessage('输出路径不能为空')
]

const convertPptxToMdValidation = [
  body('inputPath').notEmpty().withMessage('输入路径不能为空'),
  body('outputPath').notEmpty().withMessage('输出路径不能为空')
]

const convertMdToDocValidation = [
  body('inputPath').notEmpty().withMessage('输入路径不能为空'),
  body('outputPath').notEmpty().withMessage('输出路径不能为空')
]

const readFileValidation = [
  body('filePath').notEmpty().withMessage('文件路径不能为空')
]

const writeFileValidation = [
  body('filePath').notEmpty().withMessage('文件路径不能为空'),
  body('content').exists().withMessage('文件内容不能为空')
]

const listFilesValidation = [
  query('dirPath').notEmpty().withMessage('目录路径不能为空')
]

const generateLessonPlanValidation = [
  body('mdContent').notEmpty().withMessage('Markdown内容不能为空'),
  body('templateContent').notEmpty().withMessage('模板内容不能为空'),
  body('llmConfig').isObject().withMessage('LLM配置必须是对象')
]

// 路由定义
// 所有路由都需要认证和管理员权限
router.use(authenticateToken)
router.use(requireAdmin)

// Doc转Md
router.post('/convert/doc-to-md', 
  convertDocToMdValidation,
  validateRequest,
  LessonPlanController.convertDocToMd
)

// PPTX转Md
router.post('/convert/pptx-to-md', 
  convertPptxToMdValidation,
  validateRequest,
  LessonPlanController.convertPptxToMd
)

// Md转Doc
router.post('/convert/md-to-doc', 
  convertMdToDocValidation,
  validateRequest,
  LessonPlanController.convertMdToDoc
)

// 读取文件
router.post('/file/read', 
  readFileValidation,
  validateRequest,
  LessonPlanController.readFile
)

// 写入文件
router.post('/file/write', 
  writeFileValidation,
  validateRequest,
  LessonPlanController.writeFile
)

// 获取文件列表
router.get('/files', 
  listFilesValidation,
  validateRequest,
  LessonPlanController.listFiles
)

// 生成教案
router.post('/generate', 
  generateLessonPlanValidation,
  validateRequest,
  LessonPlanController.generateLessonPlan
)

// 文件上传
router.post('/upload',
  upload.single('file'),
  body('targetPath').notEmpty().withMessage('目标路径不能为空'),
  validateRequest,
  LessonPlanController.uploadFile
)

module.exports = router